package com.jieli.bt.att.ui.common

import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothProfile
import android.content.Context
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.jieli.bt.att.MyApplication
import com.jieli.bt.att.data.device.DeviceConnection
import com.jieli.bt.att.tool.ble.BleManager
import com.jieli.bt.att.tool.ble.interfaces.BleEventCallback
import com.jieli.bt.att.util.BluetoothUtil

/**
 * BluetoothViewModel
 * @author zqjasonZhong
 * @since 2025/3/28
 * @email zhongzhuocheng@zh-jieli.com
 * @desc 蓝牙基础逻辑实现
 */
open class BluetoothViewModel : ViewModel() {
    protected val tag: String = javaClass.simpleName

    protected val bleManager: BleManager = BleManager.getInstance()

    val btStateMLD = MutableLiveData<Boolean>()

    val deviceStateMLD = MutableLiveData<DeviceConnection>()

    private val btCallback = object : BleEventCallback() {

        override fun onAdapterChange(bEnabled: Boolean) {
            btStateMLD.postValue(bEnabled)
        }

        override fun onBleConnection(device: BluetoothDevice?, status: Int) {
            device?.let {
                deviceStateMLD.postValue(DeviceConnection(it, status))
            }
        }
    }

    init {
        bleManager.registerBleEventCallback(btCallback)
    }

    override fun onCleared() {
        super.onCleared()
        bleManager.unregisterBleEventCallback(btCallback)
    }

    fun getContext():Context = MyApplication.application

    fun getDeviceConnection(device: BluetoothDevice?): Int {
        if (null == device) return BluetoothProfile.STATE_DISCONNECTED
        if (bleManager.isConnectedDevice(device)) return BluetoothProfile.STATE_CONNECTED
        if (BluetoothUtil.deviceEquals(
                device,
                bleManager.connectingDevice
            )
        ) return BluetoothProfile.STATE_CONNECTING
        return BluetoothProfile.STATE_DISCONNECTED
    }
}